package com.hongxun.design;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.hongxun.design.acceptance.mode.problemExist;
import com.hongxun.design.acceptance.mode.problemExistPhoto;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.BitTypeActivity;
import com.hongxun.design.activitys.EncyclopediasActivity;
import com.hongxun.design.activitys.HomePageActivity;
import com.hongxun.design.activitys.LoginActivity;
import com.hongxun.design.activitys.ReconnaissanceActivity;
import com.hongxun.design.bean.BitTypeTabItemBean;
import com.hongxun.design.bean.CodeSetBean;
import com.hongxun.design.bean.ConsumerInfo;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.MyNewBean;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.bean.ScheduleCountBean;
import com.hongxun.design.bean.SetPointInfItemBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.service.CacheDialog;
import com.hongxun.design.ui.switchview.SwitchView;
import com.hongxun.design.utils.StringUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.gpsutil.GPS_TOOL;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.httputil.HttpUtil;
import com.hongxun.design.utils.maputil.MyBaiduSDKUSE;
import com.hongxun.design.utils.pathutil.ClipPathUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;
import com.hongxun.design.utils.shareutil.ShareUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static android.os.Environment.DIRECTORY_DOWNLOADS;


/**
 * Created by zerdoor_pc on 2016/4/18.
 */
public class MyApp extends Application {
    public static boolean isNewAdd = true;
    public static String AppName = "PEIWANG";
    public static String openIdent = "";
    public static boolean isServer = false;
    public static boolean NetWorkConnect = false;
    public static boolean ISOUTLOGIN = false;
    public static boolean isgetMessage = false;
    public static boolean iscreate = false;
    public static boolean isupdate = false;
    public static Typeface font;
    public static Context context;
    public static BaseActivity activity;//当前activity
    public static HomePageActivity HomeActivity;//首页activity
    public static Handler handler, lineTypeHandler;
    public static Handler delectHandler;//删除踏勘点
    public static BDLocation bdLocation;
    public static float zoom = 19.0f;
    public static List<BaseActivity> activities;
    public static HttpUtil HTTP;
    public static FileUtil File;
    public static ShareUtil SHARE;
    public static CodeSetBean codeSetBean = null;
    public static int addNum = 15;
    public static boolean isOnLine = false;//是否在线
    /**
     * 临时数据*
     */
    public static ProjectItemBean oldProject = new ProjectItemBean();//原来项目
    public static ProjectItemBean currProject = new ProjectItemBean();//当前项目
    public static ProjectItemBean createProject = new ProjectItemBean();//创建项目
    public static Exploration currExploration = new Exploration();//当前点位
    public static boolean isDistance = false;//是否是选择了档距之后设置的上联设备
    public static String distanceName = "";//上联名称
    public static String distanceCode = "";//上联编号
    public static Exploration currparmsExploration = new Exploration();//当前上传点位

    public static List<BitTypeTabItemBean> BitData = new ArrayList<>();//点位类型集
    // public static BitTypeTabItemBean Bitbean;//点位类型跳转——踏勘点类型数据
    //public static String reconnaissanceBean;
    public static List<SetPointInfItemBean> setPointList = new ArrayList<>();//点位设置界面数据
    public static int BackActivity = 0;//踏勘返回标识/0返回定位界面/1返回项目地图
    public static ScheduleCountBean scheduleCountBean;//首页项目统计数
    public static boolean ReadOnly = false;//踏勘完成
    //    public static boolean ReadOnly2 = false;//交付完成
    private static MyApp instance;
    /**
     * GPS数据*
     */
    public static int time = 1;//gps更新时间间隔
    public static int distence = 10;//gps更新位移间隔
    public static int POWER = Criteria.POWER_HIGH;//gps耗电量
    public static int GPSACCURACY = 5;//gps数据过滤默认精度
    public static double curr_lat = 0.00020;
    public static double curr_lon = 0.01;
    public static int currSize = 5;
    public static Location location;//GPS数据
    public static GPS_TOOL gps_tool;//GPS工具
    public static boolean change = false;//GPS工具
    public static String voltage_grade = "";//GPS工具
    /**
     * 个人账户信息*
     */
    public static ConsumerInfo userInfo = new ConsumerInfo();
    /**
     * 推送*
     */
    public static PushAgent mPushAgent;
    public static String PushType = "NetWork";

    private int activityCount;//activity的count数
    private boolean isForeground;//是否在前台

    //临时项目点位信息：用于点位坐标修改参照
    public static List<Exploration> explorationList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
//        CrashHandler.getInstance().init(getApplicationContext());//异常控制

        File path = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
        if (!path.exists()) {
            path.mkdirs();
        }
        SDKInitializer.initialize(path.getAbsolutePath(), getApplicationContext());
//        SDKInitializer.initialize(getApplicationContext());

        inIt();
        GetLocation();
        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_UM_NORMAL);
        gps_tool = GPS_TOOL.getIntence(getApplicationContext());
        gps_tool.openGPSSettings();

    }


    public static MyApp getInstance() {
        if (instance == null) {
            instance = new MyApp();
        }
        return instance;
    }

    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    /**
     * 各类组件初始化*
     */
    private void inIt() {
        if (ShardPreferencesTool.getshare(this, MString.isfirst, true)) {
            ShardPreferencesTool.saveshare(this, MString.isfirst, false);
            ShardPreferencesTool.saveshare(this, MString.Secretkey, "(ANDROIDPEIWANGPSWLOGINACTIVITY)");
        }
        context = getApplicationContext();
        isOnLine = ShardPreferencesTool.getshare(context, MString.IsOnLine, true);
        font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");//初始化字体文件
        Fresco.initialize(context);//Fresco初始化

        activities = new ArrayList<>();//activity管理
        HTTP = HttpUtil.getIntence();
        File = FileUtil.getInstence(context);
        checkNetWorkConnect();
        inItHander();//多用接收器
        getDataForOutLine();//离线信息
        inItShare();
        registerUM();

    }


    /**
     * 离线信息*
     */
    public void getDataForOutLine() {
        addLineTypeHandler();//导线型号接收器
        inItSystemData();//获取平台配置信息
        getWireList();//获取导线型号数据
    }


    /**
     * 分享初始化*
     */

    private void inItShare() {
        SHARE = ShareUtil.getInstence();
        SHARE.InIt();
    }

    /**
     * 推送设置别名*
     */
    public static void OpenPush() {
//        mPushAgent = PushAgent.getInstance(context);
        /**初始化推送**/
        try {
            mPushAgent.enable(new IUmengCallback() {
                @Override
                public void onSuccess() {
                    MyLog.L(MString.SUCCESSED + "enable 成功");
                }

                @Override
                public void onFailure(String s, String s1) {
                    MyLog.L(MString.SUCCESSED + "enable onFailure");
                }
            });
        } catch (Exception e) {
            MyLog.L(MString.FALSE + e.getMessage());
            Log.d("MyApp", MString.FALSE + e.getMessage());
        } finally {
            mPushAgent.setDebugMode(false);
            mPushAgent.setPushIntentServiceClass(MyPushIntentService.class);
        }
    }

    public static void addRedPoint() {
        MyApp.isgetMessage = true;
        MyApp.activity.Nofity();
    }

    public void registerUM() {
        mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                MyLog.L(MString.SUCCESSED + "注册成功 device_token= " + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                MyLog.L(MString.SUCCESSED + "注册失败 s= " + s + " s1= " + s1);
            }
        });

        mPushAgent.setNoDisturbMode(0, 0, 0, 0);//关闭免打扰
        mPushAgent.setDisplayNotificationNumber(0);//设置最大显示条数可以设置为0~10之间任意整数。当参数为0时，表示不合并通知。
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
    }

    public static void pushClick(MyNewBean b) {
        Bundle bundle = new Bundle();
        if (b.getObject_type().equals(MString.code_zero)) {//系统消息
            if (!b.getId().equalsIgnoreCase(MString.code_zero)) {
                bundle.putString(MString.CODE, b.getId());
                bundle.putString(MString.id, b.getObject_id());
                bundle.putString(MString.TITLE, b.getTitle());
                bundle.putString(MString.CONTENT, b.getContent());
                bundle.putString(MString.TYPE, MString.MYSYSTEM);
                IntentToActivity.intentFlag(activity, EncyclopediasActivity.class, bundle);
            } else {
                ToastShow.showShort(activity, "此消息不存在！");
            }
        } else if (b.getObject_type().equals(MString.code_one)) {

            List<ProjectItemBean> data = GetFileUtil.getProjectStageListFile();
            for (ProjectItemBean p : data) {
                if (!b.getObject_type().equalsIgnoreCase(MString.code_null) && !b.object_id.equalsIgnoreCase(MString.code_zero) && p.getStage_id().equalsIgnoreCase(b.getObject_id())) {
                    DataFactory.ProjectClick(activity, p);//点击判断函数
                    return;
                }
            }
            ToastShow.showShort(activity, "此项目不存在！");
        }

        MyApp.isgetMessage = false;
        MyApp.activity.Nofity();
    }

    public static void setAlias() {
//        OpenPush();
//        try {
//            MyLog.L(MString.SUCCESSED + "userInfo=" + userInfo.getUser_id() + " device_token=" + UmengRegistrar.getRegistrationId(activity));
//            mPushAgent.deleteAlias(userInfo.getUser_id(), PushType);
//            mPushAgent.setAlias(userInfo.getUser_id(), PushType);
//            mPushAgent.setExclusiveAlias(userInfo.getUser_id(), PushType);
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        MyLog.L(MString.SUCCESSED + "在线绑定 device_token=" + UmengRegistrar.getRegistrationId(activity));
//                        mPushAgent.removeAlias(userInfo.getUser_id(), MyApp.PushType);
//                        mPushAgent.addAlias(userInfo.getUser_id(), PushType);
//                        mPushAgent.addExclusiveAlias(userInfo.getUser_id(), PushType);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }).start();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        OpenPush();
        try {
            mPushAgent.removeAlias(userInfo.getUser_id(), PushType, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    MyLog.L(MString.SUCCESSED + "removeAlias  isSuccess= " + isSuccess + "  message=" + message);
                    mPushAgent.addAlias(userInfo.getUser_id(), PushType, new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            MyLog.L(MString.SUCCESSED + "addAlias  isSuccess= " + isSuccess + "  message=" + message);
                        }
                    });

                    mPushAgent.addExclusiveAlias(userInfo.getUser_id(), PushType,
                            new UTrack.ICallBack() {
                                @Override
                                public void onMessage(boolean isSuccess, String message) {
                                    MyLog.L(MString.SUCCESSED + "addExclusiveAlias  isSuccess= " + isSuccess + "  message=" + message);
                                }
                            });
                }
            });


            MyLog.L(MString.SUCCESSED + " getUser_id=" + userInfo.getUser_id() + " device_token= " + mPushAgent.getRegistrationId());


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 关闭推送*
     */
    public static void closePush() {
        mPushAgent.disable(new IUmengCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }


    public static void checkNetWorkConnect() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != mobNetInfo) {
            NetWorkConnect = !(!mobNetInfo.isConnected() && !wifiNetInfo.isConnected());
        } else {
            NetWorkConnect = wifiNetInfo.isConnected();
        }
        MyLog.L(MString.SUCCESSED + "  NetWorkConnect=" + NetWorkConnect);
    }

    /**
     * 初始化(系统)hander*
     */
    private void inItHander() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case Constant.HomeActivityCheck:
                        if (HomeActivity != null) {
                            HomeActivity.clickButton((String) msg.obj);
                        }
                        break;
                    case HttpStringUtil.SUCCESSED:
                        File.SaveFileData(MString.File_sysType, (String) msg.obj);
                        SaveCode((String) msg.obj);
                        break;
                    case HttpStringUtil.ERROR:
                        if (msg.obj.equals(MString.Connection)) {
                            SaveCode(File.getJson(MString.File_sysType));
                        }
                        break;
                    case Constant.GPSUpdate:
                        MyLog.L(MString.SUCCESSED + " GPS=" + location.getLatitude() + " " + location.getLongitude());
                        ReconnaissanceActivity.setUpdateGps();
                        break;

                    case Constant.GPSCloseUpdate:
                        MyLog.L(MString.SUCCESSED + " GPS=" + location.getLatitude() + " " + location.getLongitude());
                        ReconnaissanceActivity.setCloseUpdateGps();
                        break;
                    case Constant.GPSCodeUpdate:
                        MyLog.L(MString.SUCCESSED + " GPS=" + location.getLatitude() + " " + location.getLongitude());
                        ReconnaissanceActivity.setUpdateGpsCode();
                        break;

                    case Constant.GPSCodeUpdate2:
                        ReconnaissanceActivity.setUpdateGpsCode((String) msg.obj);
                        break;
                    case Constant.GPSOpenDialog:
                        ReconnaissanceActivity.setGpsDialog();
                        break;
                    case 7:
                        try {
                            if (mPushAgent != null)
                                mPushAgent.removeAlias(userInfo.getUser_id(), PushType, new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean isSuccess, String message) {
                                    }
                                });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (MyApp.userInfo != null) MyApp.userInfo.clearBean();//清理个人信息
                        if (MyApp.userInfo != null) MyApp.currProject.clearBean();//清理项目
                        MyApp.ISOUTLOGIN = true;
                        MyApp.iscreate = true;
                        if (MyApp.HomeActivity != null) MyApp.HomeActivity.closeService();
                        if (MyApp.activity != null) {
                            IntentToActivity.intent(MyApp.activity, LoginActivity.class);
                            MyApp.activity.finish();
                        }
                        break;
                    case 8://缓存典设版本
                        getCodesetType();
                        break;
                    case 9:
                        getDataForOutLine();
                        break;
                }
            }
        };
    }

    /**
     * 初始化hander*
     */
    public static void inItDelectHander() {
        delectHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String code = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (code.equals(MString.TRUE)) {
                            delLocalDate();
                        } else {
                            ToastShow.showShort(activity, code);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                    case 1://
                        MyApp.activity.onBackPressed();
                        break;
                }
            }
        };
    }

    //删除本地点位验收记录数据及其照片文件
    private static void delLocalDate() {
        List<problemExist> exPro = DataFactory.getExPro(context);
        List<problemExist> exProTemp = new ArrayList<>();
        exProTemp.addAll(exPro);

        List<problemExistPhoto> photos = DataFactory.getExProPh(context);
        List<problemExistPhoto> photosTemp = new ArrayList<>();
        photosTemp.addAll(photos);

        for (problemExist exist : exPro) {
            if (exist.getPointId().equals(MyApp.currExploration.getExploration_id())) {
                exProTemp.remove(exist);
                for (problemExistPhoto photo : photos) {
                    String aNull = StringUtil.getNull(photo.getProblemExistGuid());
                    if (exist.getGuid().equals(aNull)) {
                        photosTemp.remove(photo);
                        new File(photo.getPhoneUrls()).delete();
                    }
                }
            }
        }
        DataFactory.saveExPro(context, FastJsonUtil.beanToJson(exProTemp));
        DataFactory.saveExProPh(context, FastJsonUtil.beanToJson(photosTemp));
        delectHandler.sendEmptyMessage(1);
    }

    /**
     * 删除点位*
     */
    public static void delectExploration() {
        inItDelectHander();
        if (MyApp.isOnLine) {
            HTTP.delectExploration(delectHandler, HttpStringUtil.SUCCESSED, currExploration.getExploration_id());
        } else {
            SetFileUtil.delectExplorationList(currExploration);
        }
        clearPointData();
    }

    //ys删除踏勘点的验收记录xml数据
    private static void clearPointData() {
        List<problemExist> exists = DataFactory.getExPro(context);
        List<problemExistPhoto> photos = DataFactory.getExProPh(context);
        if (exists != null && !exists.isEmpty()) {
            List<problemExist> existList = new ArrayList<>();
            existList.addAll(exists);
            List<problemExistPhoto> existPhotos = new ArrayList<>();
            if (photos != null) existPhotos.addAll(photos);
            for (problemExist exist : existList) {
                boolean equals1 = exist.getProjectId().equals(currProject.getStage_id());
                boolean equals2 = exist.getPointId().equals(currExploration.getExplor_id());
                if (equals1 && equals2) {
                    //问题数据处理
                    if (exist.getStates().equals("新增")) {
                        exists.remove(exist);
                    } else {
                        int indexOf = exists.indexOf(exist);
                        exist.setStates("删除");
                        exists.set(indexOf, exist);
                    }
                    //照片数据处理
                    if (photos != null && !photos.isEmpty()) {
                        String existGuid = exist.getGuid();
                        for (problemExistPhoto photo : existPhotos) {
                            if (existGuid.equals(photo.getProblemExistGuid())) {
                                FileUtil.deleteFile(photo.getPhoneUrls());
                                if (photo.getStates().equals("新增")) {
                                    photos.remove(photo);
                                } else {
                                    int indexOf = photos.indexOf(photo);
                                    photo.setStates("删除");
                                    photos.set(indexOf, photo);
                                }
                            }
                        }
                    }
                }
            }
            DataFactory.saveExPro(context, FastJsonUtil.beanToJson(exists));
            if (photos == null) return;
            DataFactory.saveExProPh(context, FastJsonUtil.beanToJson(photos));
        }
    }

    /**
     * 初次定位*
     */
    private void GetLocation() {
        MyBaiduSDKUSE.getIntence(context).startSDK();
    }

    public static void clearActivityto(Class<? extends BaseActivity> activity) {
        MyLog.L("activitysactivitys=" + JSON.toJSONString(MyApp.activities) + " BitTypeActivity=" + BitTypeActivity.class);
        if (!activities.contains(activity)) return;
        for (int i = activities.size(); i >= 0; i--) {
            if (activities.get(i).equals(activity)) {
                break;
            } else {
                activities.get(i).onBackPressed();
            }
        }
    }

    /**
     * 获取平台配置信息*
     */
    private void inItSystemData() {
        HTTP.getSystemType(handler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 存储基本配置*
     */
    private void SaveCode(final String s) {
        if (s == null || s.length() == 0) return;
        ShardPreferencesTool.saveshare(context, MString.systemBaseInfo, s);
        new Thread(new Runnable() {
            @Override
            public void run() {
                com.alibaba.fastjson.JSONObject object = JSON.parseObject(s);
                Set<String> KEY = object.keySet();
                Object[] keys = KEY.toArray();
                for (int i = 0; i < keys.length; i++) {
                    ShardPreferencesTool.saveshare(context, keys[i].toString(), object.get(keys[i]).toString());
                }
//                /**解析方法**/
//                List<SystemTypeBean> list=FastJsonUtil.JsonToData_Code(ShardPreferencesTool.getshare(context, HttpStringCodeTableUtil.auditStatus, "")) ;

            }
        }).start();

    }

    public void saveImgTypeList(String json) {
        Log.d("MyApp", json);
        if (TextUtils.isEmpty(json.trim())) return;
        if (FastJsonUtil.JsonToCheck(json))
            ShardPreferencesTool.saverecord(context, MString.itl, json);
    }


    /**
     * 获取导线型号数据*
     */
    private void getWireList() {
        MyApp.HTTP.getWireList(lineTypeHandler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 导线型号接收器*
     */
    List<SystemTypeBean> Wire;

    private void addLineTypeHandler() {
        lineTypeHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (Wire == null) {
                                Wire = FastJsonUtil.JsonToGetWireList(String.valueOf(msg.obj));
                            } else {
                                Wire.clear();
                                Wire.addAll(FastJsonUtil.JsonToGetWireList(String.valueOf(msg.obj)));
                            }

                            ShardPreferencesTool.saveshare(context, HttpStringCodeTableUtil.WireList, (String) msg.obj);
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(Wire));
                        }
                        break;
                    case HttpStringUtil.ERROR:

                        break;

                }
            }
        };
    }

    /**
     * 获取离线典设版本信息*
     */
    public void getCodesetType() {
        List<SystemTypeBean> beans = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.codesetType);
        for (SystemTypeBean s : beans) {
            getDataForCodeSet(s.getTypecode());
        }
        getCodeSetList("", "");
    }

    /**
     * 获取离线典设版本对应信息*
     */

    private void getDataForCodeSet(String typecode) {
        MyApp.HTTP.getCodeSetVersion(addCodeSetHandler(typecode), HttpStringUtil.SUCCESSED2, typecode);
    }

    private Handler addCodeSetHandler(final String typecode) {
        Handler codeSetHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED2:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
//                            String code= (String) msg.obj;
                            ShardPreferencesTool.saveshare(context, MString.codeset_type + typecode, (String) msg.obj);
//                            if (code.length()>0){
//                                List<CodeSetVersionBean> versionBeans= FastJsonUtil.JsonToData_CodeSetVersion(code);
//                                for (CodeSetVersionBean c:versionBeans){//遍历典设版本
//                                    String codeset_version_id= c.getCodeset_version_id();
//                                    getCodeSetList(codeset_version_id,"");
//                                }
//                            }

                        }
                        break;
                    case HttpStringUtil.ERROR:

                        break;
                    default:
                        break;
                }
            }
        };
        return codeSetHandler;
    }

    public void getCodeSetList(String codeset_version_id, String pt_id) {
        MyApp.HTTP.getCodeSetList(AddChoiceModelHandler(), HttpStringUtil.SUCCESSED2, codeset_version_id, pt_id, null, 0, Integer.MAX_VALUE, MString.click_in);

    }

    private Handler AddChoiceModelHandler() {
        Handler choiceModelHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED2:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            ShardPreferencesTool.saveshare(MyApp.activity, MString.CodeSetList, (String) msg.obj);
                        }
                        CacheDialog.getInstence().getHandler().sendEmptyMessage(0);
                        break;
                    case HttpStringUtil.ERROR:
                        CacheDialog.getInstence().getHandler().sendEmptyMessage(1);
                        break;
                }
            }
        };
        return choiceModelHandler;
    }


    /**
     * 项目切换*
     */
    public static void ChangeToNewProject(ProjectItemBean itembean) {
        if (!itembean.getStage_id().equals(MyApp.currProject.getProject_id())) {
            //切换项目
            if ((oldProject.getStage_id().length() == 0 || oldProject.getStage_id().equals(MString.code_zero))
                    && oldProject.getUUID().length() == 0) {
                oldProject.setBean(currProject, 1);
            }
            currProject.setBean(itembean);
            //MyApp.currProject.setProject_name(itembean.getProject_name());
            if (ReconnaissanceActivity.headsecond_layout != null)
                ReconnaissanceActivity.headsecond_layout.setSearchTitle(currProject.getProject_name());

            ReconnaissanceActivity.setNew();

        }
    }

    public static void ChangeToOldProject() {
        if (oldProject.getStage_id() != null && !oldProject.getStage_id().equals(MString.code_zero)
                && (oldProject.getStage_id().length() > 0 || oldProject.getUUID().length() > 0)) {
            currProject.setBean(oldProject);
            oldProject.clearBean();
        }
    }


    //离线状态
    public static void ChangeToOffLine() {
        isOnLine = false;
        ShardPreferencesTool.saveshare(activity, MString.IsOnLine, false);
    }

    //在线状态
    public static void ChangeToOnLine(SwitchView view) {
        switchView = view;
        HTTP.ConsumerInfo(onlineCheckHandler, HttpStringUtil.SUCCESSED);
    }

    static SwitchView switchView;
    private static Handler onlineCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dellMsg(msg);
        }
    };

    private static void dellMsg(Message msg) {
        switch (msg.what) {
            case HttpStringUtil.SUCCESSED:
                if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                    ConsumerInfo info = FastJsonUtil.JsonToLoginData((String) msg.obj);
                    if (info != null && info.getOrg_id().equalsIgnoreCase(MyApp.userInfo.getOrg_id())) {
                        isOnLine = true;
                        ShardPreferencesTool.saveshare(activity, MString.IsOnLine, true);
                        switchView.toggleSwitch(false);//在线
                    } else {
                        ToastShow.showShort(activity, "用户单位已变化,请重新登录");
                        try {
                            MyApp.mPushAgent.removeAlias(userInfo.getUser_id(), PushType, new UTrack.ICallBack() {
                                @Override
                                public void onMessage(boolean isSuccess, String message) {
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        MyApp.userInfo.clearBean();//清理个人信息
                        MyApp.currProject.clearBean();//清理项目
                        MyApp.ISOUTLOGIN = true;
                        MyApp.iscreate = true;
                        if (MyApp.HomeActivity != null) MyApp.HomeActivity.closeService();
                        IntentToActivity.intent(activity, LoginActivity.class);
                        activity.finish();
                    }

                } else {
                    switchView.toggleSwitch(true);//离线
                    ChangeToOffLine();
                    ToastShow.showShort(activity, FastJsonUtil.JsonToCheck_String((String) msg.obj) + ",离线转在线失败！");
                }


                break;
            case HttpStringUtil.ERROR:
                switchView.toggleSwitch(true);//离线
                ChangeToOffLine();
                ToastShow.showShort(activity, msg.obj + ",离线转在线失败！");
                break;
        }
    }

    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null, bitmap1 = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            bitmap1 = CameraUtil.compressImage(bitmap);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap1;
    }

    public static Bitmap byFresco(String picUrl) {
        final Bitmap[] bitMap = {null};
        Uri uri = Uri.parse(picUrl);
        ImageDecodeOptions decodeOptions = ImageDecodeOptions.newBuilder()
                .setBackgroundColor(Color.GRAY)
                .build();
        ImageRequest imageRequest = ImageRequestBuilder
                .newBuilderWithSource(uri)
                .setImageDecodeOptions(decodeOptions)
                .setAutoRotateEnabled(true)
                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH)
                .setProgressiveRenderingEnabled(false)
                .setResizeOptions(new ResizeOptions(480, 800))
                .build();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
        dataSource.subscribe(new BaseBitmapDataSubscriber() {
            @Override
            protected void onNewResultImpl(Bitmap bitmap) {
                bitMap[0] = bitmap;
            }

            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

            }
        }, UiThreadImmediateExecutorService.getInstance());
        return bitMap[0];
    }

    /**
     * 下载语音*
     */
    public static String getHttpVoice(String url, String PATH) {
        if (!PATH.contains("voice.amr") && (new java.io.File(PATH)).exists()) return PATH;

        if (PATH.equals(url)) return PATH;
        String httpurl = "";

        if (url.equals("voice.amr")) {
            return MyApp.File.getCachaPhotoVoicePath() + url;
        } else if (url.contains(MyApp.File.getCachaPath() + "") || url.contains(ClipPathUtil.getInstance().getVoicePath() + "")) {
            MyApp.File.copyFile(url, PATH);
            return PATH;
        } else if (!url.contains(HttpStringUtil.HeadSpeech)) {
            if (url.indexOf("/") == 0) {
                httpurl = HttpStringUtil.HeadSpeech + url;
            } else {
                httpurl = HttpStringUtil.HeadSpeech + "/" + url;
            }
        } else {
            httpurl = url;
        }

        if (url.contains(HttpStringUtil.HeadSpeech) && PATH.contains(MyApp.File.getCachaPhotoVoicePath()) && !isOnLine) {//离线下不下载直接读取
            String amrpath = MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
            String mp3path = MyApp.File.getCachaPhotoVoicePath() + "voice.mp3";
            File amrfile = new File(amrpath);
            File mp3file = new File(mp3path);
            if (amrfile.exists()) {
                return amrpath;
            }
            if (mp3file.exists()) {
                return mp3path;
            }
            return MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
        }
        MyLog.L(MString.SUCCESSED + " 下载语音：" + httpurl);

        if (httpurl.contains("mp3")) {
            PATH = PATH.replaceAll("voice.amr", "voice.mp3");
        }
        MyLog.L(MString.SUCCESSED + " 下载到：" + PATH);
        HTTP.download(httpurl, PATH);
        return PATH;


    }

//    public static String getHttpVoice(String url, String PATH) {
//        String[] tar=url.split("/");
//        String name="";
//        if (tar.length>0){
//            name=tar[tar.length-1];
//        }else{
//            name=tar[0];
//        }
//
//        PATH=PATH+name;
//        if (PATH.equals(url)) return PATH;
//
//        String httpurl = "";
//        java.io.File file=new File(PATH);
//        if (file.exists()){
//            return PATH;
//        }else if (url.contains(MyApp.File.getCachaPath() + "") || url.contains(ClipPathUtil.getInstance().getVoicePath() + "")) {
//            MyApp.File.copyFile(url, PATH);
//            return PATH;
//        } else if (!url.contains(HttpStringUtil.HeadSpeech)) {
//            if (url.indexOf("/") == 0) {
//                httpurl = HttpStringUtil.HeadSpeech + url;
//            } else {
//                httpurl = HttpStringUtil.HeadSpeech + "/" + url;
//            }
//        } else {
//            httpurl = url;
//        }


//        if (PATH.equals(url)) return PATH;
//        String httpurl = "";
//
//        if (url.equals("voice.amr")) {
//            return MyApp.File.getCachaPhotoVoicePath() + url;
//        } else if (url.contains(MyApp.File.getCachaPath() + "") || url.contains(ClipPathUtil.getInstance().getVoicePath() + "")) {
//            MyApp.File.copyFile(url, PATH);
//            return PATH;
//        } else if (!url.contains(HttpStringUtil.HeadSpeech)) {
//            if (url.indexOf("/") == 0) {
//                httpurl = HttpStringUtil.HeadSpeech + url;
//            } else {
//                httpurl = HttpStringUtil.HeadSpeech + "/" + url;
//            }
//        } else {
//            httpurl = url;
//        }
//
//        if (url.contains(HttpStringUtil.HeadSpeech) && PATH.contains(MyApp.File.getCachaPhotoVoicePath()) && !isOnLine) {//离线下不下载直接读取
//            return MyApp.File.getCachaPhotoVoicePath() + name;
//        }
//        MyLog.L(MString.SUCCESSED + " 下载语音：" + httpurl);
//        MyLog.L(MString.SUCCESSED + " 下载到：" + PATH);
//        HTTP.download(httpurl, PATH);
//        return PATH;
//    }

    public static void checkPriess() {
        if (activity == null) return;
        PackageManager pm = activity.getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.RECORD_AUDIO", "packageName"));
        if (permission) {
            // showToast("有这个权限");
        } else {
            // showToast("木有这个权限");
        }
    }
}
